/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rultax.blackice.physics.example;

import com.rultax.blackice.physics.processing.ProcessingPhysics;
import com.rultax.blackice.physics.processing.ProcessingObject;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PVector;

/**
 *
 * @author Scott
 */
public class Box extends ProcessingObject{

    private Body body;
    private float w;
    private float h;
    
    public Box(float x, float y, PApplet parent, ProcessingPhysics physics){
        super(parent, physics);
        
        w = getParent().random(4, 16);
        h = getParent().random(4, 16);
        
        makeBody(new PVector(x, y));
    }
    
    public void killBody(){
        getPhysics().destroyBody(body);
    }
    
    public boolean done(){
        PVector pos = getPhysics().getBodyScreenCoord(body);
        if(pos.y > getParent().height + w * h){
            killBody();
            return true;
        }
        return false;
    }
    
    @Override
    public void display() {
        PVector pos = getPhysics().getBodyScreenCoord(body);
        float a = body.getAngle();
        
        getParent().rectMode(PConstants.CENTER);
        getParent().pushMatrix();
        getParent().translate(pos.x, pos.y);
        getParent().rotate(-a);
        getParent().fill(175);
        getParent().stroke(0);
        getParent().rect(0, 0, w, h);
        getParent().popMatrix();
    }
    
    private void makeBody(PVector center){
        BodyDef bd = new BodyDef();
        bd.type = BodyType.DYNAMIC;
        
        bd.position.set(getPhysics().coordScreenToWorld(center));
        body = getPhysics().createBody(bd);
        
        body.setLinearVelocity(new Vec2(getParent().random(-5, 5),getParent().random(2, 5)));
        body.setAngularVelocity(getParent().random(-5,5));
        
        PolygonShape ps = new PolygonShape();
        float box2dw = getPhysics().scalarScreenToWorld(w / 2);
        float box2dh = getPhysics().scalarScreenToWorld(h / 2);
        ps.setAsBox(box2dw, box2dh);
        
        FixtureDef fd = new FixtureDef();
        fd.shape = ps;
        fd.density = 1.0f;
        fd.friction = 0.3f;
        fd.restitution = 0.5f;
        
        body.createFixture(fd);
    }
    
    @Override
    public String toString(){
	return "Box: " + body.getPosition().x + ", " + body.getPosition().y;
    }
}
